{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '3'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [EOS] for i in train_Y]\n",
    "test_Y = [i + [EOS] for i in test_Y]\n",
    "train_X = [i + [EOS] for i in train_X]\n",
    "test_X = [i + [EOS] for i in test_X]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import defaultdict\n",
    "\n",
    "BASE_PARAMS = defaultdict(\n",
    "    lambda: None,  # Set default value to None.\n",
    "\n",
    "    # Input params\n",
    "    default_batch_size=2048,  # Maximum number of tokens per batch of examples.\n",
    "    default_batch_size_tpu=32768,\n",
    "    max_length=256,  # Maximum number of tokens per example.\n",
    "\n",
    "    # Model params\n",
    "    initializer_gain=1.0,  # Used in trainable variable initialization.\n",
    "    vocab_size=vocab_size,  # Number of tokens defined in the vocabulary file.\n",
    "    hidden_size=512,  # Model dimension in the hidden layers.\n",
    "    num_hidden_layers=6,  # Number of layers in the encoder and decoder stacks.\n",
    "    num_heads=8,  # Number of heads to use in multi-headed attention.\n",
    "    filter_size=2048,  # Inner layer dimension in the feedforward network.\n",
    "\n",
    "    # Dropout values (only used when training)\n",
    "    layer_postprocess_dropout=0.1,\n",
    "    attention_dropout=0.1,\n",
    "    relu_dropout=0.1,\n",
    "\n",
    "    # Training params\n",
    "    label_smoothing=0.1,\n",
    "    learning_rate=1.0,\n",
    "    learning_rate_decay_rate=1.0,\n",
    "    learning_rate_warmup_steps=16000,\n",
    "\n",
    "    # Optimizer params\n",
    "    optimizer_adam_beta1=0.9,\n",
    "    optimizer_adam_beta2=0.997,\n",
    "    optimizer_adam_epsilon=1e-09,\n",
    "\n",
    "    # Default prediction params\n",
    "    extra_decode_length=50,\n",
    "    beam_size=4,\n",
    "    alpha=0.6,  # used to calculate length normalization in beam search\n",
    "\n",
    "    # TPU specific parameters\n",
    "    use_tpu=False,\n",
    "    static_batch=False,\n",
    "    allow_ffn_pad=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/translation/transformer/attention_layer.py:24: The name tf.layers.Layer is deprecated. Please use tf.compat.v1.layers.Layer instead.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "from transformer.transformer import Transformer\n",
    "from transformer import utils\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, train = True, learning_rate = 1e-4):\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        model = Transformer(BASE_PARAMS, train)\n",
    "        self.training_logits = model(self.X, self.Y)\n",
    "        self.training_logits = self.training_logits[:, :tf.reduce_max(self.Y_seq_len)]\n",
    "        self.training_logits = pad_second_dim(self.training_logits, tf.reduce_max(self.Y_seq_len))\n",
    "        \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "#         self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "#                                                      targets = self.Y,\n",
    "#                                                      weights = masks)\n",
    "        \n",
    "        xentropy, weights = utils.padded_cross_entropy_loss(\n",
    "            self.training_logits, self.Y, BASE_PARAMS[\"label_smoothing\"], BASE_PARAMS[\"vocab_size\"])\n",
    "        self.cost = tf.reduce_sum(xentropy) / tf.reduce_sum(weights)\n",
    "        self.xentropy = xentropy\n",
    "        self.weights = weights\n",
    "        \n",
    "#         optimizer = tf.contrib.opt.LazyAdamOptimizer(\n",
    "#             BASE_PARAMS['learning_rate'],\n",
    "#             beta1=BASE_PARAMS[\"optimizer_adam_beta1\"],\n",
    "#             beta2=BASE_PARAMS[\"optimizer_adam_beta2\"],\n",
    "#             epsilon=BASE_PARAMS[\"optimizer_adam_epsilon\"])\n",
    "        \n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate,\n",
    "                                               beta1=BASE_PARAMS[\"optimizer_adam_beta1\"],\n",
    "                                                beta2=BASE_PARAMS[\"optimizer_adam_beta2\"],\n",
    "                                                epsilon=BASE_PARAMS[\"optimizer_adam_epsilon\"]).minimize(self.cost)\n",
    "        \n",
    "#         global_step = tf.train.get_global_step()\n",
    "#         tvars = tf.trainable_variables()\n",
    "#         gradients = optimizer.compute_gradients(\n",
    "#             self.cost, tvars, colocate_gradients_with_ops=True)\n",
    "#         minimize_op = optimizer.apply_gradients(\n",
    "#             gradients, global_step=global_step, name=\"train\")\n",
    "#         update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n",
    "#         self.optimizer = tf.group(minimize_op, update_ops)\n",
    "\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n",
    "        \n",
    "        self.fast_result = model(self.X)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From /home/husein/translation/transformer/attention_layer.py:39: The name tf.layers.Dense is deprecated. Please use tf.compat.v1.layers.Dense instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/translation/transformer/transformer.py:84: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/translation/transformer/model_utils.py:89: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n",
      "WARNING:tensorflow:From /home/husein/translation/transformer/embedding_layer.py:48: The name tf.AUTO_REUSE is deprecated. Please use tf.compat.v1.AUTO_REUSE instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/translation/transformer/embedding_layer.py:51: The name tf.get_variable is deprecated. Please use tf.compat.v1.get_variable instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/autograph/converters/directives.py:119: The name tf.rsqrt is deprecated. Please use tf.math.rsqrt instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/translation/transformer/ffn_layer.py:65: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:From /home/husein/translation/transformer/ffn_layer.py:65: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n",
      "WARNING:tensorflow:From /home/husein/translation/transformer/model_utils.py:71: The name tf.matrix_band_part is deprecated. Please use tf.linalg.band_part instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/translation/transformer/utils.py:82: The name tf.log is deprecated. Please use tf.math.log instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/translation/transformer/beam_search.py:420: calling reduce_logsumexp_v1 (from tensorflow.python.ops.math_ops) with keep_dims is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "keep_dims is deprecated, use keepdims instead\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(train = False)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'outputs': array([[ 7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "           7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "           7843, 29821, 29821, 29821, 29821, 29821, 29821, 29821, 29821,\n",
       "          29821, 29821, 29821, 29821, 29821, 29821, 29821, 29821, 29821,\n",
       "          29821, 29821, 29821, 29821, 29821, 29821, 29821, 29821, 29821,\n",
       "          29821, 29821, 29821, 29821, 29821, 29821, 29821, 29821, 29821,\n",
       "          29821, 11702, 11702, 11702, 11702, 11702, 11702, 11702, 11702,\n",
       "          11702, 11702, 11702, 11702, 11702, 11702, 11702, 11702, 11702,\n",
       "          11702, 11702, 11702, 11702, 11702, 11702, 11702, 11702, 11702,\n",
       "          11702, 11702, 11702, 11702, 11702, 11702],\n",
       "         [ 7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "           7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "           7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "           7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "           7843,  7843,  7843,  7843,  7843,  5789,  5789,  5789,  5789,\n",
       "           5789,  5789,  5789,  5789,  5789,  5789,  5789,  5789,  5789,\n",
       "           5789,  5789,  5789,  5789,  5789,  5789,  5789,  5789,  5789,\n",
       "           5789,  5789,  5789,  5789,  5789,  5789,  5789,  5789,  5789,\n",
       "           5789,  5789,  5789,  5789,  5789,  5789,  5789,  5789,  5789,\n",
       "           5789,  5789,  5789,  5789,  5789,  5789],\n",
       "         [24113, 24113, 24113, 24113, 24113, 24113, 24113, 24113, 24113,\n",
       "          24113, 24113, 24113, 24113, 24113, 24113, 24113, 24113, 24113,\n",
       "          24113, 24113, 24113, 24113, 24113, 24113, 24113, 24113, 24113,\n",
       "          24113, 24113, 24113, 24113, 24113, 24113, 24113, 24113, 24113,\n",
       "          24113, 24113, 24113, 24113, 24113, 24113, 24113, 24113, 24113,\n",
       "          24113, 24113, 24113, 24113, 24113, 24113, 24113, 24113, 24113,\n",
       "          24113, 24113, 24113, 24113, 24113, 24113, 24113, 24113, 24113,\n",
       "          24113, 28542, 28542, 28542, 28542, 28542, 28542, 28542, 28542,\n",
       "          28542, 28542, 28542, 28542, 28542, 28542, 28542, 28542, 28542,\n",
       "          28542, 28542, 28542, 28542, 28542, 28542],\n",
       "         [ 7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "           7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "          12633, 12633, 12633, 12633, 12633, 12633, 12633, 12633, 12633,\n",
       "          12633, 12633, 12633, 12633, 12633, 12633, 12633, 12633, 12633,\n",
       "          12633, 12633, 12633, 12633, 12633, 12633, 12633, 12633, 12633,\n",
       "          12633, 12633, 12633, 12633, 12633, 12633, 12633, 12633, 12633,\n",
       "          12633, 12633, 12633, 12633, 12633, 12633, 12633, 12633, 12633,\n",
       "          12633, 12633, 12633, 12633, 12633, 12633, 12633, 12633, 12633,\n",
       "          12633, 12633, 12633, 12633, 12633, 12633, 12633, 12633, 12633,\n",
       "          12633, 12633, 12633, 12633, 12633, 12633],\n",
       "         [26920, 26920, 26920, 26920, 26920, 26920, 26920, 26920, 26920,\n",
       "          26920, 26920, 26920, 26920, 26920, 26920, 26920, 26920, 26920,\n",
       "          26920, 26920, 26920, 26920, 26920, 26920, 26920, 26920, 26920,\n",
       "          26920, 26920, 26920, 26920, 26920, 26920, 26920, 26920, 26920,\n",
       "          26920, 26920, 26920, 26920, 26920, 26920, 26920, 26920, 26920,\n",
       "          26920, 26920, 26920, 26920, 26920, 26920, 26920, 26920, 26920,\n",
       "          26920, 26920, 26920, 26920, 26920, 26920, 26920, 26920, 26920,\n",
       "          26920, 26920, 26920, 26920, 26920, 26920, 26920, 26920, 26920,\n",
       "          26920, 26920, 26920, 26920, 26920, 26920, 26920, 26920, 26920,\n",
       "          26920, 26920, 26920, 26920, 26920, 26920],\n",
       "         [ 7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "           7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "           7843,  7843, 31971, 31971, 31971, 31971, 31971, 31971, 31971,\n",
       "          31971, 31971, 31971, 31971, 31971, 31971, 31971, 31971, 31971,\n",
       "          31971, 31971, 31971, 31971, 31971, 31971, 31971, 31971, 31971,\n",
       "          31971, 31971, 31971, 31971, 31971, 31971, 31971, 31971, 31971,\n",
       "          31971, 31971, 31971, 31971, 31971, 31971, 31971, 31971, 31971,\n",
       "          31971, 31971, 31971, 31971, 31971, 31971, 31971, 31971, 31971,\n",
       "          31971, 31971, 31971, 31971, 31971, 31971, 31971, 31971, 31971,\n",
       "          31971, 31971, 31971, 31971, 31971, 31971],\n",
       "         [ 7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "           7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "           7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "           7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "           7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "           7843,  7843,  9038,  9038,  9038,  9038,  9038,  9038,  9038,\n",
       "           9038,  9038,  9038,  9038,  9038,  9038,  9038,  9038,  9038,\n",
       "           9038,  9038,  9038,  9038,  9038,  9038,  9038,  9038,  9038,\n",
       "           9038,  9038,  9038,  9038,  9038,  9038,  9038,  9038,  9038,\n",
       "           9038,  9038,  9038,  9038,  9038,  9038],\n",
       "         [ 7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "           7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "           7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "           7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "           7843,  7843,  7843, 16679, 16679, 16679, 16679, 16679, 16679,\n",
       "          16679, 16679, 16679, 16679, 16679, 16679, 16679, 16679, 16679,\n",
       "          16679, 16679, 16679, 16679, 16679, 16679, 16679, 16679, 16679,\n",
       "          16679, 16679, 16679, 16679, 16679, 16679, 16679, 16679, 16679,\n",
       "          16679, 16679, 16679, 16679, 16679, 16679, 16679, 16679, 16679,\n",
       "          16679, 16679, 16679, 16679, 16679, 16679],\n",
       "         [20256, 20256, 20256, 20256, 20256, 20256, 20256, 20256, 20256,\n",
       "          20256, 20256, 20256, 20256, 20256, 20256, 20256, 20256, 20256,\n",
       "          20256, 20256, 20256, 20256, 20256, 20256, 20256, 20256, 11702,\n",
       "          11702, 11702, 11702, 11702, 11702, 11702, 11702, 11702, 11702,\n",
       "          11702, 11702, 11702, 11702, 11702, 11702, 11702, 11702, 11702,\n",
       "          11702, 11702, 11702, 11702, 11702, 11702, 11702, 11702, 11702,\n",
       "          11702, 11702, 11702, 11702, 11702, 11702, 11702, 11702, 11702,\n",
       "          11702, 11702, 11702, 11702, 11702, 11702, 11702, 11702, 11702,\n",
       "          11702, 11702, 11702, 11702, 11702, 11702, 11702, 11702, 11702,\n",
       "          11702, 11702, 11702, 11702, 11702, 11702],\n",
       "         [ 7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "           7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "           7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "           7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "           7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,  7843,\n",
       "           7843,  7843,  7843,  7843,  7843,  7843, 16679, 16679, 16679,\n",
       "          16679, 16679, 16679, 16679, 16679, 16679, 16679, 16679, 16679,\n",
       "          16679, 16679, 16679, 16679, 16679, 16679, 16679, 16679, 16679,\n",
       "          16679, 16679, 16679, 16679, 16679, 16679, 16679, 16679, 16679,\n",
       "          16679, 16679, 16679, 16679, 16679, 16679]], dtype=int32),\n",
       "  'scores': array([-168.1183  , -127.506546, -139.3419  , -137.75621 , -117.58283 ,\n",
       "         -146.28534 , -137.3829  , -142.91571 , -138.62807 , -139.07626 ],\n",
       "        dtype=float32)},\n",
       " 9.59,\n",
       " 0.0]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:59<00:00,  2.61it/s, accuracy=0.311, cost=4.12] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.85it/s, accuracy=0.355, cost=3.69]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 4.931033, training avg acc 0.231605\n",
      "epoch 1, testing avg loss 3.965092, testing avg acc 0.325697\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:59<00:00,  2.61it/s, accuracy=0.436, cost=3.08]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.73it/s, accuracy=0.452, cost=3.01]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 3.495378, training avg acc 0.379644\n",
      "epoch 2, testing avg loss 3.223244, testing avg acc 0.413091\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:55<00:00,  2.63it/s, accuracy=0.516, cost=2.47]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.69it/s, accuracy=0.505, cost=2.61]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 2.810910, training avg acc 0.465626\n",
      "epoch 3, testing avg loss 2.803579, testing avg acc 0.465993\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:00<00:00,  2.60it/s, accuracy=0.59, cost=2.02] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.17it/s, accuracy=0.548, cost=2.37]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 2.377887, training avg acc 0.525493\n",
      "epoch 4, testing avg loss 2.594180, testing avg acc 0.494423\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:55<00:00,  2.62it/s, accuracy=0.651, cost=1.69]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.69it/s, accuracy=0.559, cost=2.35]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 2.083165, training avg acc 0.570465\n",
      "epoch 5, testing avg loss 2.508307, testing avg acc 0.508869\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:45<00:00,  2.42it/s, accuracy=0.714, cost=1.38]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.68it/s, accuracy=0.538, cost=2.34]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 1.859793, training avg acc 0.607867\n",
      "epoch 6, testing avg loss 2.486385, testing avg acc 0.509901\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:56<00:00,  2.62it/s, accuracy=0.768, cost=1.17]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.71it/s, accuracy=0.543, cost=2.3] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 1.676332, training avg acc 0.641557\n",
      "epoch 7, testing avg loss 2.478976, testing avg acc 0.512768\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:55<00:00,  2.63it/s, accuracy=0.815, cost=0.967]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.66it/s, accuracy=0.538, cost=2.31]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 1.515637, training avg acc 0.673292\n",
      "epoch 8, testing avg loss 2.511891, testing avg acc 0.511439\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:54<00:00,  2.63it/s, accuracy=0.847, cost=0.824]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.73it/s, accuracy=0.559, cost=2.47]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 1.374782, training avg acc 0.702964\n",
      "epoch 9, testing avg loss 2.570941, testing avg acc 0.508078\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:54<00:00,  2.63it/s, accuracy=0.878, cost=0.698]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.73it/s, accuracy=0.543, cost=2.48]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 1.243936, training avg acc 0.732496\n",
      "epoch 10, testing avg loss 2.631162, testing avg acc 0.502554\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:54<00:00,  2.63it/s, accuracy=0.906, cost=0.597]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.68it/s, accuracy=0.532, cost=2.57]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 1.123974, training avg acc 0.761155\n",
      "epoch 11, testing avg loss 2.710203, testing avg acc 0.497635\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:53<00:00,  2.63it/s, accuracy=0.917, cost=0.554]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.71it/s, accuracy=0.538, cost=2.71]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 1.015994, training avg acc 0.788118\n",
      "epoch 12, testing avg loss 2.808853, testing avg acc 0.494065\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:54<00:00,  2.63it/s, accuracy=0.951, cost=0.472]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.72it/s, accuracy=0.548, cost=2.76]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 0.917788, training avg acc 0.813549\n",
      "epoch 13, testing avg loss 2.900151, testing avg acc 0.492411\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:54<00:00,  2.63it/s, accuracy=0.942, cost=0.459]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.74it/s, accuracy=0.565, cost=2.82]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 0.832055, training avg acc 0.836703\n",
      "epoch 14, testing avg loss 2.924478, testing avg acc 0.492939\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:53<00:00,  2.63it/s, accuracy=0.967, cost=0.394]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.73it/s, accuracy=0.543, cost=2.87]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 0.753824, training avg acc 0.858470\n",
      "epoch 15, testing avg loss 2.987153, testing avg acc 0.487956\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:53<00:00,  2.63it/s, accuracy=0.97, cost=0.383] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.72it/s, accuracy=0.548, cost=2.86]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 0.682485, training avg acc 0.878942\n",
      "epoch 16, testing avg loss 3.047732, testing avg acc 0.485624\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:40<00:00,  2.44it/s, accuracy=0.984, cost=0.357]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.71it/s, accuracy=0.559, cost=2.99]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 0.621172, training avg acc 0.896736\n",
      "epoch 17, testing avg loss 3.123955, testing avg acc 0.478847\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:53<00:00,  2.64it/s, accuracy=0.982, cost=0.36] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.71it/s, accuracy=0.559, cost=2.96]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 0.569504, training avg acc 0.911538\n",
      "epoch 18, testing avg loss 3.145874, testing avg acc 0.483298\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop:  62%|██████▏   | 964/1563 [06:04<03:33,  2.81it/s, accuracy=0.925, cost=0.529]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [03:12<00:00,  4.81s/it]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)['outputs']\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 1])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.17100729"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
